package com.ui.zhixiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ui.zhixiao.common.CustomException;
import com.ui.zhixiao.domain.*;
import com.ui.zhixiao.mapper.CategoryMapper;
import com.ui.zhixiao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{
    @Autowired
    private AnswerService answerService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService ;
    /**
     * 根据id删除分类 删除之前判断是否关联文章或者答题
     * @param id
     */
    @Override
    public void remove(Long id) {
        //查询分类是否关联文章
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.eq(Article::getCategoryId,id);
        int articlecount = articleService.count(articleLambdaQueryWrapper);
        if(articlecount>0){
            //已经关联文章 抛出业务异常
            throw new CustomException("当前分类下关联了文章，无法删除");
        }


        //查询分类是否关联答题
        LambdaQueryWrapper<Answer> answerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        answerLambdaQueryWrapper.eq(Answer::getCategoryId,id);
        int answercount = answerService.count(answerLambdaQueryWrapper);
        if(answercount>0){
            //已经关联答题 抛出业务异常
            throw new CustomException("当前分类下关联了答题，无法删除");
        }

        super.removeById(id);
//    =====================================================================================================================================
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据分类id查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(dishLambdaQueryWrapper);
        //查询当前分类是否关联了菜品
        if(count1>0){
            //已经关联菜品 抛出业务异常
            throw new CustomException("当前分类下关联了菜品，无法删除");
        }


        //查询分类是否关联套餐
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = answerService.count(answerLambdaQueryWrapper);
        if(count2>0){
            //已经关联套餐 抛出业务异常
            throw new CustomException("当前分类下关联了套餐，无法删除");
        }

        super.removeById(id);
    }
}
